<template>
  <a-modal :title="title" :width="1250" :visible="visible"  @cancel="handleCancel"
    :cancelText="$t('systemManagement.close')" wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <a-button style="margin-left: 8px" v-print="'#reportPrintDetail'" icon="printer">{{$t('reportQuery.print')}}</a-button>   
      <a-button v-if="btnEnableList.indexOf(5) > -1"  style="margin-left: 8px" @click="generatePrintData" icon="printer">{{$t('inPrint.other') + $t('reportQuery.print')}}</a-button>
      <a-button style="margin-left: 8px" @click="handleCancel">{{$t('systemManagement.close')}}</a-button>   
               
    </template>
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper" v-if="selectType === 'list'">
      <!-- 搜索区域 -->
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="24">
            <a-form-item :label="$t('defaultTranslate.operator')" :labelCol="{ span: 5 }"
              :wrapperCol="{ span: 18, offset: 1 }">
              <a-select :placeholder="$t('inPrint.selectPerson')" style="width: 200px" v-model="queryParam.creator">
                <a-select-option v-for="(item,index) in userList" :key="index" :value="item.id">
                {{ item.userName }}
                  </a-select-option>
                </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item :label="$t('reportQuery.customer')" :labelCol="{ span: 5 }"
              :wrapperCol="{ span: 18, offset: 1 }">
              <a-select :placeholder="$t('reportQuery.selectCustomer')" v-model="queryParam.organId"
                 showSearch>
                <a-select-option v-for="(item,index) in cusList" :key="index" :value="item.id">
                  {{ item.supplier }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item :label="$t('setailManagement.documentDate')" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-range-picker style="width: 100%" v-model="queryParam.createTimeRange" format="YYYY-MM-DD"
                :placeholder="[$t('setailManagement.startTime'), $t('setailManagement.endTime')]" @change="onDateChange"
                :default-value="defaultTimeStr"
                @ok="onDateOk" />
            </a-form-item> 
          </a-col>
          <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="searchQuery">{{ $t('setailManagement.query') }}</a-button>
              <a-button style="margin-left: 8px" @click="searchReset">{{ $t('setailManagement.reset') }}</a-button>
              <a-button v-if="btnEnableList.indexOf(3) > -1" :loading="downLoading" style="margin-left: 8px" @click="exportExcel" icon="download">{{$t('reportQuery.export')}}</a-button>
            </a-col>
          </span>
        </a-row>
      </a-form>
    </div>
    <!-- table区域-begin -->
    <section ref="print" id="reportPrintDetail">
    <a-table v-if="selectType === 'list'" bordered ref="table" size="middle" :columns="columns"
      :dataSource="dataSource" :pagination="ipagination" :loading="loading"
      :selection="{key:'id'}"
      :customRow="rowAction" @change="handleTableChange">
      <span slot="numberCustomRender" slot-scope="text, record">
        <a @click="myHandleDetail(record)">{{ record.number }}</a>
      </span>
    </a-table>
    </section>

    <!-- table区域-end -->
    <!-- 表单区域 -->
    <bill-detail ref="billDetail"></bill-detail>
  </a-modal>
</template>

<script>
import BillDetail from '@/views/bill/dialog/BillDetail'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { findBillDetailByNumber,findBySelectSup,findBySelectCus,getUserList  } from '@/api/api'
import { getAction } from '@/api/manage'
import Vue from 'vue'
  import { getMpListShort,getNowFormatYear,openDownloadDialog, sheet2blob } from "@/utils/util"
  import { titleObj,accountReportType,billDetailRemarks } from '@/lang/category'
  import {getLanCode} from '@/lang';
import moment from 'moment';
import { subtract } from 'lodash'
export default {
  name: 'LinkBillList',
  mixins: [JeecgListMixin],
  components: {
    BillDetail ,
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      }
  },
  data() {
    return {
      title: this.$t('reportQuery.employeeReportDetail'),
      visible: false,
      disableMixinCreated: true,
      selectedRowKeys: [],
      selectedDetailRowKeys: [],
      selectBillRows: [],
      selectedRows:[],
      selectBillDetailRows: [],
      showType: 'basic',
      selectType: 'list',
      linkNumber: '',
      deliveryMethod: '',
      arrivalTimeStr: '',
      organId: '',
      depotId: '',
      discount: '',
      deposit: '',
      remark: '',
      checkDepotId:'',
      linkId:'',
      supList:[],
      cusList:[],
      userList:[],
      defaultTimeStr:undefined,
      queryParam: {
        organId: undefined,
        creator:undefined,
        beginTime: getNowFormatYear() + '-01-01',
        endTime: moment().format('YYYY-MM-DD'),
      },
      noNeedNextDialogArray: ['ZPHX', 'ZFYS', 'YSKD', 'FYF','YFKD'],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      // 表头
      columns: [
      // <!-- 订单号，金额，销售类型，折扣金额，退货金额，总额 -->

        {
          title: this.$t('reportQuery.documentNo'), dataIndex: 'number', width: 150,
          scopedSlots: { customRender: 'numberCustomRender' },
        },
        // { title: this.$t('金额'), dataIndex: 'totalPrice', width: 145 },
        {
          title: this.$t('otherJS.DocumentType'), dataIndex: 'newType', width: 80, ellipsis: true,
            customRender:function (t,r,index) {
              let flag = getLanCode() === 'en'
              // let text = t.replace(/入库/g,'')
              return flag ? accountReportType[t] || t : t
            }
        },
        { title: this.$t('otherJS.discountAmount'), dataIndex: 'discountAllPrice', width: 70 },
        { title: this.$t('reportQuery.returnAmount'), dataIndex: 'returnMoney', width: 70 },
        {
          title: this.$t('purchasingManagement.eachAmount'), dataIndex: 'totalPrice', width: 70,
          customRender: function (text, record, index) {
            if (record.discountLastMoney && record.discountMoney ) {
              return (record.discountMoney + record.discountLastMoney).toFixed(2);
            } else {
              return record.totalPrice;
            }
          }
        },
        { title: this.$t('salesManagement.operator'), dataIndex: 'loginName', width: 70 },
        { title: this.$t('setailManagement.documentDate'), dataIndex: 'createTime', width: 120, 
          customRender: function (text, record, index) {
              return moment(record.createTime).format('YYYY-MM-DD HH:mm:ss')
          }
        },
        // {
        //   title: this.$t('setailManagement.state'), dataIndex: 'status', width: 70, align: "center",
        //   scopedSlots: { customRender: 'customRenderStatus' }
        // }
      ],
      dataSource: [],
      dataSourceDetail: [],
      url: {
        list: "/depotHead/findDepotByCreatorDetail"
      }
    }
  },
  created() {
    this.defaultTimeStr = [moment(getNowFormatYear() + '-01-01', this.dateFormat), moment(this.currentDay, this.dateFormat)]
  },
  methods: {
    moment,
    initCustomer () {
      let that = this
      findBySelectCus({}).then(res => {
        if (res) {
          that.cusList = res
        }
      })
    },
    show(record,param,btnEnableList) {
      this.btnEnableList = btnEnableList
      this.queryParam.creator = record.creator
      this.queryParam.organId = ''
      this.$set(this.queryParam,'createTimeRange',param.createTimeRange)
      this.$set(this.queryParam,'beginTime',param.beginTime)
      this.$set(this.queryParam,'endTime',param.endTime)
      this.initCustomer()
      this.initUser()
      this.loadData(1)
      this.visible = true
    },


    getType: function () {
      const checkboxArr = [];
      if (checkboxArr.includes(this.queryParam.prefixNo)) {
        return 'checkbox'
      }
      return 'radio';
    },

    myHandleDetail(record) { 
      findBillDetailByNumber({ number: record.number }).then((res) => {
        if (res && res.code === 200) {
          let type = res.data.depotHeadType
          type = type.replace('其它', '')
          this.$refs.billDetail.show(res.data, type)
          this.$refs.billDetail.title = type + "-" + '详情'
        }
      })
    },
    setColumns(columns,columnsDetail){
      if(columns && columns.length){
        this.columns = columns
      }
      if(columnsDetail && columnsDetail.length){
        this.columnsDetail = columnsDetail
        console.log(this.columnsDetail,999);
      }
    },
    close() {
      this.$emit('close');
      this.visible = false;
    },
    handleCancel() {
      this.close()
    },
    onSelectChange(selectedRowKeys,selectedRows) {
      console.log(selectedRowKeys,666);
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows.map(v=>v.id)
    },
    onSelectDetailChange(selectedRowKeys) {
      this.selectedDetailRowKeys = selectedRowKeys;
    },
    organChenge(e){
      let arr = this.dataSourceDetail.filter(v=>v.organId === e)
      this.selectedDetailRowKeys = arr.map(v=>v.id)
    },
    handleOk() {
      
    },
    onDateChange: function (value, dateString) {
      this.queryParam.beginTime = dateString[0];
      this.queryParam.endTime = dateString[1];
    },
    onDateOk(value) {
      console.log(value);
    },
    searchReset() {
      this.queryParam = {
        organId: undefined,
        creator:undefined,
        beginTime: getNowFormatYear() + '-01-01',
        endTime: moment().format('YYYY-MM-DD'),
      }
      this.loadData(1);
    },
    getSelectBillRows() {
      let dataSource = this.dataSource;
      this.selectBillRows = [];
      for (let i = 0, len = dataSource.length; i < len; i++) {
        if (this.selectedRows.includes(dataSource[i].id)) {
          this.selectBillRows.push(dataSource[i]);
        }
      }
    },
    getSelectBillDetailRows() {
      let dataSource = this.dataSourceDetail;
      this.selectBillDetailRows = [];
      for (let i = 0, len = dataSource.length; i < len; i++) {
        if (this.selectedDetailRowKeys.includes(dataSource[i].id)) {
          this.selectBillDetailRows.push(dataSource[i]);
        }
      }
    },
    rowAction(record, index) {
      return {
        on: {
          click: () => {
            let arr = []
            arr.push(record.id)
            this.selectedRowKeys = arr
          },
          dblclick: () => {
            if (this.noNeedNextDialogArray.includes(this.queryParam.prefixNo)) {
              this.$emit('ok', [record])
              this.close()
              return
            }
            let arr = []
            arr.push(record.id)
            this.selectedRows = arr
            this.handleOk()
          }
        }
      }
    },
    getQueryParams() {
      for (const key in this.queryParam) {
        if (Object.hasOwnProperty.call(this.queryParam, key)) {
          const element = this.queryParam[key];
          if(!element){
            this.queryParam[key] = ''
          }
        }
      }
        let param = Object.assign({}, this.queryParam);
        param.currentPage = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        return param;
      },
    loadData (arg) {
      console.log(this.url.list)
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }

      var params = this.getQueryParams() //查询条件
      
      this.loading = true
      getAction(this.url.list, params).then(res => {
        if (res.code === 200) {
          this.dataSource = res.data.rows.map(item => {
            !item.receivedQuantity && (item.receivedQuantity = 0)
            item.notReceived = item.total - item.receivedQuantity
            !item.billNo && (item.billNo = item.defaultNumber)
            return item
          })
          this.ipagination.total = res.data.total
          this.tableAddTotalRow(this.columns, this.dataSource)
        }
        if (res.code === 510) {
          this.$message.warning(res.data)
        }
        this.loading = false
      })
    },
    initUser () {
        getUserList({}).then((res) => {
          this.userList = res
        })
      },
      async exportExcel() {
        let aoa = [this.columns.map(v=>v.title)]
        this.downLoading = true
        // 获取要导出的数据
        let dataSource = await this.loadAllData(1)
        this.downLoading = false
        for (let i = 0; i < dataSource.length; i++) {
          let item = []
          for (let l = 0; l < this.columns.length; l++) {
            let column = this.columns[l]
              let text = dataSource[i][column.dataIndex] || ''
              // 有自定义方法
              if(typeof(column.customRender) ==="function"){
                let res = column.customRender(text,dataSource[i])
                // 返回的是node节点
                if(res && typeof(res.componentOptions)!="undefined"){
                  text = res.componentOptions.children[0].text
                }else{
                  text = res || ''
                }
              }
              item.push(text)
            
          }
          aoa.push(item)
        }
        openDownloadDialog(sheet2blob(aoa),this.title)
      },
  }
}
</script>

<style scoped>

</style>